/**
 * @Author: Jimmy
 * @Date: 2022/6/14
 * @Version: 1.0
 * @Content: 对象拷贝
 */

import { isObject } from '@utils/dataTypes'

/**
 * 深拷贝对象 数组
 * @param obj
 * @returns {any}
 */
export function deepClone(obj: object | Array<any>): object | Array<any> {
  if (isObject(obj)) {
    return deepCloneObject(obj)
  }
  if (Array.isArray(obj)) {
    return deepCloneArray(obj)
  }
  return obj
}

/**
 * 深拷贝对象
 * @param obj
 * @return {{}}
 */

interface Obj {
  [propName: string]: any
}
function deepCloneObject(obj: Obj): object {
  const cloneObj: Obj = {}
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (isObject(obj[key])) {
        cloneObj[key] = deepCloneObject(obj[key])
      } else if (Array.isArray(obj[key])) {
        cloneObj[key] = deepCloneArray(obj[key])
      } else {
        cloneObj[key] = obj[key]
      }
    }
  }
  return cloneObj
}

/**
 * 深拷贝数组
 * @param array
 * @return {*}
 */
function deepCloneArray(array: Array<any>): Array<any> {
  return array.map((item) => {
    if (isObject(item)) {
      return deepCloneObject(item)
    }
    if (Array.isArray(item)) {
      return deepCloneArray(item)
    }
    return item
  })
}
